import React, { useState } from 'react'
import { TextArea, ImageUploader, Toast } from 'antd-mobile'
import { useOssHooks } from "@/hooks/CustomOssHooks"
import "@/assets/css/addMemoire.scss"

import { useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'

import { addUserMemo } from "@/utils/dataUtil"

import HeadBack from "@/components/HeadBack"

import delImg from "@/assets/images/hospital/del_img.png"
import uploadImg from "@/assets/images/hospital/upload.png"


export default function AddMemoire() {

    const detail = useSelector((state) => state.MemoReducer.detail);

    const location = useLocation();

    const navigate = useNavigate();
    
    // 标题内容
    const [titVal, setTitVal] = useState(location.state.type === "update" && detail.title ? detail.title : "");
    // 补充内容
    const [supplyVal, setSupplyVal] = useState(location.state.type === "update" && detail.remark ? detail.remark : "");
    //图片的集合
    const [fileList, setFileList] = useState(location.state.type === "update" && detail.pics ? detail.pics.map((item) => ({url: item})) : []);
    
    //上传图片的hooks
    const {customOssRequest} = useOssHooks();
    
    //标题内容改变
    const titChange = (val) => {
        setTitVal(val);
    }
    //补充内容改变
    const supplyChange = (val) => {
        setSupplyVal(val);
    }
    
    //图片上传之前判断是否大于5M大于则不予上传
    const beforeUpload = (file) => {
        if (file.size > 1024 * 1024 * 5) {
            Toast.show('请选择小于 5M 的图片')
            return null
        }
        return new File([file], new Date().getTime() + "_" + file.name);
    }
    //图片改变的事件
    const handleChange = (newFileList) => {
        setFileList(newFileList);
    };

    //新建和修改的响应
    const publicResponse = (res) => {
        if(res.status === 1) {
            //添加成功
            Toast.show({
                content: "保存成功",
                position: 'bottom'
            });
            const timeout = setTimeout(() => {
                clearTimeout(timeout);
                if(location.state.page === "home") {
                    navigate("/memo", {replace: true})
                } else {
                    navigate(-1);
                }
            }, 1000);
        } else {
            Toast.show({
                content: `${res.msg}`,
                position: 'center'
            });
        }
    }

    //点击保存按钮
    const clickSaveBtn = () => {
        if(titVal.trim() === '') {return;}
        const param = {
            title: titVal,
            remark: supplyVal,
            pics: fileList.map((item) => item.url)
        }

        if(location.state?.type === "add") {
            addUserMemo(null, param).then(res => {
                publicResponse(res);
            })
            return;
        }

        //修改
        addUserMemo(detail.index, param).then(res => {
            publicResponse(res);
        })
    }

    



    return (
        <div className='addContainer'>
            <HeadBack background={"#FFFFFF"} backTit={""}  isHome="back"></HeadBack>


            {/* 标题和内容 */}
            <div className='addContent'>

                {/* 标题 */}
                <div className='addTit'>
                    <TextArea value={titVal} onChange={titChange} className='addTitArea' placeholder='请输入标题' showCount maxLength={20} rows={1} />
                </div>
                <div className='addSupply'>
                    <TextArea value={supplyVal} onChange={supplyChange} className='addSupplyArea' placeholder='请输入补充内容' showCount maxLength={100} />
                </div>


            </div>

            {/* 图片上传 */}
            <div className='addUploadBox'>
                <ImageUploader
                    deleteIcon={<img alt='' src={delImg} style={{width: "0.6rem", height: "0.6rem"}} />}
                    value={fileList}
                    imageFit="contain"
                    maxCount={3}
                    onChange={handleChange}
                    beforeUpload={beforeUpload}
                    upload={customOssRequest}
                >
                    {/* 自定义上传样式 */}
                    <div className='addUpload'>
                        <img alt='' src={uploadImg} className='addUploadIcon' />
                        <div className='addUploadTxt'>添加图片</div>
                    </div>
                </ImageUploader>

                {/* 上传限制提示 */}
                <div className='addUploadTip'>可选，最多3张</div>
            </div>


            {/* 保存按钮 */}
            <div className='addSaveBox'>
                <div className={`addSaveBtn ${titVal.trim() !== '' && 'addSaveBtnCur'}`} onClick={clickSaveBtn}>保存</div>
            </div>
        </div>
    )
}
